﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.ComponentModel;
using Microsoft.Practices.Unity;
using Vit.Common;
using Vit.Common.Extensions;
using Vit.Web.Mvc.DataAnnotations;
using Vit.Web.Providers;
using Vit.Web.Providers.DataSource;

namespace Vit.Web.Mvc
{
    public class DataSourceFormModelBinder : DefaultModelBinder
    {
        public DataSourceFormModelBinder()
        {
            this.DataSourceTextControlSuffix = "_Text";
        }

        protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
        {
            if (!string.IsNullOrWhiteSpace(DataSourceTextControlSuffix))
            {
                if (propertyDescriptor.Attributes.OfType<DataSourceAttribute>().Any() && value == null)
                {
                    string dataSourceText = controllerContext.HttpContext.Request[string.Concat(propertyDescriptor.Name, DataSourceTextControlSuffix)];
                    if (!string.IsNullOrWhiteSpace(dataSourceText))
                    {
                        DataSourceAttribute refAttr = propertyDescriptor.Attributes.OfType<DataSourceAttribute>().First();
                        var dataSourceProvider = Unity.Current.Resolve<IDataSourceProvider>(string.Format("DataSource:{0}", refAttr.DataSourceType.FullName));
                        if (dataSourceProvider != null)
                        {
                            value = dataSourceProvider.GetValueByText(refAttr.CategoryName, dataSourceText, true);
                        }
                    }
                }
            }

            if (typeof(DateTime).Equals(propertyDescriptor.PropertyType))
            {
                if (value == null || DateTime.Parse(value.ToString()) < new DateTime(1800, 1, 1))
                {
                    value = new DateTime(1800, 1, 1);
                }
            }

            base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
        }

        public string DataSourceTextControlSuffix { get; set; }
    }
}
